/*
 * @Author: Ethan
 * @Github: https://github.com/ethanpub
 * @Date: 2019-05-22 17:29:06
 * @LastEditors: Ethan
 * @Blog: https://ethan.pub
 * @LastEditTime: 2019-08-29 17:45:34
 * @Description: 🙏BUG退散🙏
 */
import { isDev } from '../config/index'
import { getStorage } from '@/utils/storage'
import router from '@/router'
import axios from 'axios'
import { message } from 'ant-design-vue'
import { AxiosRequestConfig } from 'axios'

export const instance = axios.create({
  baseURL: '/api',
  timeout: 15000
})

instance.interceptors.request.use(cfg => {
  cfg.headers.Token = getStorage('Token') || ''
  return cfg
})

instance.interceptors.response.use(
  res => {
    if (res.data.code === '202') {
      router.push('/')
      return
    }
    return res as any
  },
  err => {

    if (!err.response) {
      // 请求超时状态
      if (err.message.includes('timeout')) {
        console.log('超时了')
        message.error('请求超时，请检查网络是否连接正常')
      } else {
        // 可以展示断网组件
        console.log('断网了')
        message.error('请求失败，请检查网络是否已连接')
      }
      return
    }
    if (isDev) {
      err.response
        ? message.error('错误码：' + err.response.status)
        : message.error('请求超时...')
    }
    return Promise.reject(err)
  }
)

interface Response<T = any> {
  token: string
  message: string
  result?: T
  code: number
}

export const Api = <T = any>(config: AxiosRequestConfig) => {
  return instance(config).then(({ data }) => data as Response<T>)
}
